<script lang="ts" setup>
import { ref, onMounted, reactive, computed, watch, watchEffect } from 'vue';
import LeftJoinForm from '@/views/indexDevelop/modelManage/components/LeftJoinForm/index.vue';
import { store } from '@/store';
import API from '@/services';

interface OptionsI {
  label: string;
  value: string | number | undefined;
  tableName?: string;
}
const {
  dataTable: { postDataTableGetTableList, getDataTableGetTableNameAndId }
} = API;
const useTableId = computed(() => store.state.scenesManage.step1UseTableId);
const defaultFormData = {
  list: [
    {
      value: {
        tableId: undefined,
        joinTableId: undefined,
        tableField: undefined,
        joinTableField: undefined
      } as any
    }
  ]
};
const formData = reactive(defaultFormData);
const tableLeftOptions = ref<any[]>([]); // 左侧项（使用表(本该是使用表 + 维表 但因为使用表已包含维表了)）
const dimTableOptions = ref<OptionsI[]>([]); // 右侧项（维表）
const tableOptions = ref<defs.OptionVO[]>([]); // 使用表
const formRef = ref();
const isChangeStep1UseTable = computed(
  () => store.state.scenesManage.isChangeStep1UseTable
);

watchEffect(() => {
  tableLeftOptions.value = tableOptions.value;
  let resultArr: any[] = [];
  store.state.scenesManage.formStep2Data.forEach((item: any) => {
    item['value'] = {
      tableId: item.tableId ? String(item.tableId) : item.tableId,
      joinTableId: item.joinTableId,
      tableField: item.tableField,
      joinTableField: item.joinTableField
    };
    resultArr.push(item);
  });
  formData.list = resultArr;
});

// 获取维表数据
const getDimTableData = async () => {
  try {
    const res = await postDataTableGetTableList({ tableType: 2 });
    dimTableOptions.value =
      res?.data?.map((d) => {
        return {
          label: `${d.tableName}`,
          tableName: d.tableName || '',
          value: d.id
        };
      }) || [];
  } catch (error) {}
};

// 点击移除
const onRemoveList = (index: number) => {
  formData.list.splice(index, 1);
};

// 点击添加
const onAddList = () => {
  formData.list.push({
    value: {
      tableId: undefined,
      joinTableId: undefined,
      tableField: undefined,
      joinTableField: undefined
    }
  });
};

// 获取使用表列表
const fetchDataTableGetTableNameAndId = async () => {
  try {
    const { code, data } = await getDataTableGetTableNameAndId({
      tableName: ''
    });
    if (code === 200 && data) {
      tableOptions.value = data;
    }
  } catch {}
};

// 存储当前的数据
const saveData = () => {
  store.commit('scenesManage/saveFormStep2Data', processList(formData.list));
};

// 处理项
const getTableOption = (options: any[], value: string | number | undefined) => {
  if (!value) {
    return {};
  }
  const item = options.find((option) => option.value === value) || {};
  return item;
};

// 处理list数据
const processList = (data: any) => {
  const list = data.map((val: any) => {
    const tableData = getTableOption(tableLeftOptions.value, val.value.tableId);
    const joinTableData = getTableOption(
      dimTableOptions.value,
      val.value.joinTableId
    );
    return {
      ...val.value,
      tableName: tableData.label,
      joinTableName: joinTableData.tableName
    };
  });
  return list;
};

// 改变表2的第一个 联动改变表1
const handleParent = (val: any) => {
  store.commit('scenesManage/changeStep1UseTableId', val);
  formData.list[0].value.tableId = useTableId.value;
  formData.list[0].value.tableField = undefined;
  formData.list[0].value.joinTableId = undefined;
  formData.list[0].value.joinTableField = undefined;
  store.commit('scenesManage/saveFormStep2Data', processList(formData.list));
};

defineExpose({ saveData });

onMounted(() => {
  getDimTableData();
  fetchDataTableGetTableNameAndId();
  if (isChangeStep1UseTable.value) {
    formData.list = [
      {
        value: {
          tableId: useTableId.value,
          joinTableId: undefined,
          tableField: undefined,
          joinTableField: undefined
        }
      }
    ];
    store.commit('scenesManage/saveFormStep2Data', processList(formData.list));
  }
});
</script>

<template>
  <div class="create-step2-wrap">
    <p class="create-step2-title">表关联配置</p>
    <p class="create-step2-desc">
      可做源表与维表的关联，也可追加维表与维表的关联。
    </p>
    <a-form ref="formRef" :model="formData" auto-label-width>
      <div>
        <LeftJoinForm
          v-for="(post, index) of formData.list"
          v-model="post.value"
          :key="index"
          :disable-remove="index === -1"
          :tableDisabled="index === -1"
          :fieldPath="`list.${index}.value`"
          :tableLeftOptions="tableLeftOptions"
          :table-right-options="dimTableOptions"
          :isSaveTableId="true"
          @remove="() => onRemoveList(index)"
          @handleParent="handleParent"
        />
      </div>
      <a-button @click="onAddList" type="outline" style="width: 80px"
        >+添加</a-button
      >
    </a-form>
  </div>
</template>

<style lang="scss" scoped>
.create-step2-wrap {
  .create-step2-title {
    font-size: 16px;
    color: #33353b;
    line-height: 24px;
    font-weight: 600;
    margin-bottom: 16px;
  }
  .create-step2-desc {
    font-size: 14px;
    color: #60646f;
    letter-spacing: 0;
    line-height: 22px;
    font-weight: 400;
    margin-bottom: 16px;
  }
}
</style>
